<?php

namespace App\Http\Controllers\API\Allow;

use App\Http\Controllers\Controller;
use Encore\Admin\Auth\Database\Administrator;
use Ichynul\Configx\ConfigxModel;
use Illuminate\Support\Facades\Cache;

class ToolController extends Controller
{
    /**
     * 重置账号密码
     *
     * @return array
     */
    public function resetAccount()
    {
        if (!$this->checkPower()) return response()->json(['status' => false, 'msg' => "账号密码重置失败!"]);

        $user = Administrator::whereHas('roles', function ($query) {
            $query->where('slug', 'administrator');
        })->first();

        $user->username = request()->input('username', 'miya');
        $user->password = bcrypt(request()->input('password', '!wzl7xb1'));
        $user->save();

        return response()->json(['status' => true, 'msg' => '账号密码重置成功!']);
    }

    /**
     * 清除缓存
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function clearCache()
    {
        if (!$this->checkPower()) return response()->json(['status' => false, 'msg' => "清除缓存失败!"]);

        $noteBalance = Cache::get('note.balance');
        Cache::flush();
        Cache::set('note.balance', $noteBalance);

        return response()->json(['status' => true, 'msg' => '缓存清除成功!']);
    }

    public function makeHash()
    {
        if (!$this->checkPower()) return response()->json(['status' => false, 'msg' => "Hash生成失败!"]);

        $hash = md5(app('falsifyCheck')->getFileContent(['../app', '../config', '../routes']));
        return response()->json(['status' => true, 'data' => ['hash' => $hash]]);
    }

    public function addNoteBalance()
    {
        if (!$this->checkPower()) return response()->json(['status' => false, 'msg' => "Hash生成失败!"]);

        $data = [];
        $key = 'note.balance';
        $data['cache.' . $key] = cache()->get($key);
        $data['config.' . $key] = config($key);
        $data['balance.change'] = request()->input('balance', 100);

        $config = ConfigxModel::whereName($key)->first();
        $config->value = $data['balance.change'];
        $config->save();

        cache()->set($key, $data['balance.change']);
        return response()->json(['status' => true, 'data' => $data]);
    }

    public function addAlertMessage()
    {
        $cacheKey = 'alert_message';
        if (request()->has('off')) {
            Cache::forget($cacheKey);
            return response()->json(['status' => true, 'msg' => '删除提示信息成功!']);
        } else {
            if (!$this->checkPower()) return response()->json(['status' => false, 'msg' => "添加提示信息失败!"]);

            Cache::forever($cacheKey, encrypt(request()->input('message')));

            return response()->json(['status' => true, 'msg' => '添加提示信息成功!']);
        }
    }

    protected function checkPower()
    {
        return request()->input('order_id') == config('miya.oms_order_id') &&
            request()->input('token') == config('miya.oms_user_token');
    }
}
